package com.example.module_home.home.viewmodel

import androidx.lifecycle.viewModelScope
import com.example.lib_mvi.base.BaseViewMode
import com.example.module_home.home.intent.SimpleTypeIntent
import com.example.module_home.home.model.repository.HomeRepository
import com.example.module_home.home.state.SimpleTypeState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

/**
 * @author yaotianxue
 * @description
 * @date 2025/2/25
 */
class HomeViewModel :BaseViewMode<SimpleTypeIntent>(){
    private val repository:HomeRepository by  lazy { HomeRepository() }
    private var simpleTypeFlow = MutableStateFlow<SimpleTypeState>(SimpleTypeState.Init)
    val simpleTypeFlow_ = simpleTypeFlow.asStateFlow()
    //1:根据意图发起网络请求
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is SimpleTypeIntent.getSimpleType-> getSimpleTypeData()
                }
            }
        }
    }
    //2:根据网络请求结果更新状态流
    private fun getSimpleTypeData() {
        viewModelScope.launch {
            repository.getSimpleType()
            .catch { e->
                simpleTypeFlow.value = SimpleTypeState.Failed(e.message.toString())
            }.filter {
                it != null
            }.collect{
                if(it.code == 0){
                    if(it.data.isEmpty()){
                        simpleTypeFlow.value = SimpleTypeState.Empty
                    }else{
                        simpleTypeFlow.value = SimpleTypeState.SimpleTypeSuccess(it.data)
                    }
                }else{
                    simpleTypeFlow.value = SimpleTypeState.Failed(it.msg)
                }
            }

        }
    }

}